package cn.sjxy.service;

import cn.sjxy.baseLib.SjuException;
import cn.sjxy.mapper.Mp_BookInfo;
import cn.sjxy.mapper.Mp_BookType;
import cn.sjxy.model.Md_BookInfo;
import cn.sjxy.model.Md_BookType;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * 图书信息业务逻辑层
 */
@Service
public class Sv_BookInfo {

    @Autowired
    private Mp_BookInfo mp_bookInfo;

    @Autowired
    private Mp_BookType mp_bookType;

    /**
     * 获取图书详情（带类型名称）
     * @param id
     * @return
     */
    public Md_BookInfo getBookDetail(Long id) {
        Md_BookInfo bookInfo = mp_bookInfo.selectById(id);
        if (bookInfo != null) {
            // 查询类型名称
            QueryWrapper<Md_BookType> typeWrapper = new QueryWrapper<>();
            typeWrapper.eq("typeCode", bookInfo.getTypeCode());
            Md_BookType bookType = mp_bookType.selectOne(typeWrapper);
            if (bookType != null) {
                bookInfo.setTypeName(bookType.getTypeName());
            }
        }
        return bookInfo;
    }

    /**
     * 检查图书编号是否存在
     * @param bookCode
     * @param excludeId 排除的ID（用于修改时）
     * @return
     */
    public boolean isBookCodeExist(String bookCode, Long excludeId) {
        QueryWrapper<Md_BookInfo> wrapper = new QueryWrapper<>();
        wrapper.eq("bookCode", bookCode);
        if (excludeId != null) {
            wrapper.ne("id", excludeId);
        }
        Long count = mp_bookInfo.selectCount(wrapper);
        return count > 0;
    }

    /**
     * 图书上架
     * @param id
     * @throws Exception
     */
    public void toSell(Long id) throws Exception {
        Md_BookInfo bookInfo = mp_bookInfo.selectById(id);
        if (bookInfo == null) {
            SjuException.appEx("图书不存在");
        }
        bookInfo.setIsSell("是");
        mp_bookInfo.updateById(bookInfo);
    }

    /**
     * 图书下架
     * @param id
     * @throws Exception
     */
    public void toNoSell(Long id) throws Exception {
        Md_BookInfo bookInfo = mp_bookInfo.selectById(id);
        if (bookInfo == null) {
            SjuException.appEx("图书不存在");
        }
        bookInfo.setIsSell("否");
        mp_bookInfo.updateById(bookInfo);
    }
}

